package xyz.labmem.base.sys.module.log.controller

import cn.dev33.satoken.stp.StpUtil
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.web.bind.annotation.*
import xyz.labmem.base.core.annotion.BusinessLog
import xyz.labmem.base.core.enums.LogAnnotationOpTypeEnum
import xyz.labmem.base.core.result.RV
import xyz.labmem.base.sys.base.BaseController
import xyz.labmem.base.sys.consts.PathPrefixConst
import xyz.labmem.base.sys.context.AuthRedisService
import xyz.labmem.base.sys.module.log.entity.SysUserOnline
import xyz.labmem.base.sys.util.LogManager
import java.util.*

@RestController
@Api(tags = ["在线人数"])
@RequestMapping("${PathPrefixConst.SYS_PATH_PREFIX}online")
class SysUserOnlineController(
    private var authRedisService: AuthRedisService
): BaseController()   {

    @ApiOperation(value = "分页查询在线人数")
    @GetMapping("/page")
    fun page(ipaddr: String?, userName: String?): RV<MutableList<SysUserOnline>> {
        //拼接redisKey前缀
        val tokenRedisKey = "Authorization-satoken:login:token:"
        val userOnlineList: MutableList<SysUserOnline> = ArrayList<SysUserOnline>()

        var start = -1
        var size = 100

        while (true) {
            //获取 redis 中所有Token   keyword 关键字   start 开始处索引 (-1代表查询所有)  size 获取数量
            val tokenList = StpUtil.searchTokenValue("", start, size)
            if (tokenList.isEmpty()) {
                break
            }
            start = size + 1
            size = start + 100
            for (token in tokenList) {
                //切割结果集
                val split = token.split(tokenRedisKey.toRegex()).toTypedArray()
                //获取token
                val tokenString = split[1]
            //    authRedisService.getUserEntity(tokenString)?.let { userOnlineList.add(it) }
                getOnlineUserByToken(tokenString)?.let { userOnlineList.add(it) }
            }
        }
        Collections.reverse(userOnlineList)
        userOnlineList.removeAll(setOf<Any?>(null))
        return success(userOnlineList)
    }

    /**
     * 强退用户
     */
    @ApiOperation(value = "强退用户")
    @BusinessLog(title = "强退用户", opType = LogAnnotationOpTypeEnum.FORCE)
    @DeleteMapping("/{tokenId}")
    fun forceLogout(@PathVariable tokenId: String): RV<*> {

        LogManager.me().executeExitLog(getOnlineUserByToken(tokenId)?.userName)
    //    authRedisService.removeUserEntity(StpUtil.getLoginIdByToken(tokenId).toString(),tokenId)
        StpUtil.logoutByTokenValue(tokenId)
        return success()
    }
}